package com.lixin.smartclassroom.common

import android.animation.Animator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.drake.brv.utils.bindingAdapter
import com.drake.channel.sendEvent
import com.drake.net.utils.scopeNet
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.adddianping
import com.lixin.smartclassroom.api.addteachers
import com.lixin.smartclassroom.api.addtop
import com.lixin.smartclassroom.api.bindcustomer
import com.lixin.smartclassroom.api.canaddcustomer
import com.lixin.smartclassroom.api.classlist
import com.lixin.smartclassroom.api.createfolder
import com.lixin.smartclassroom.api.createyanxuegroup
import com.lixin.smartclassroom.api.deletebigzhangjie
import com.lixin.smartclassroom.api.deletecourse
import com.lixin.smartclassroom.api.deletefolder
import com.lixin.smartclassroom.api.deletesmallzhangjie
import com.lixin.smartclassroom.api.fabucourse
import com.lixin.smartclassroom.api.folderlist
import com.lixin.smartclassroom.api.getzhutitype
import com.lixin.smartclassroom.api.huizhanglist
import com.lixin.smartclassroom.api.lablelist
import com.lixin.smartclassroom.api.openorclosesmallzhangjie
import com.lixin.smartclassroom.api.openorclosezhangjie
import com.lixin.smartclassroom.api.shangchaunfile
import com.lixin.smartclassroom.api.updatefolder
import com.lixin.smartclassroom.api.updatejingcaifile
import com.lixin.smartclassroom.api.uploadFiles
import com.lixin.smartclassroom.api.weidulist
import com.lixin.smartclassroom.api.yanxuebaominglist
import com.lixin.smartclassroom.api.yanxuebiaoqian
import com.lixin.smartclassroom.api.yanxuegroupstudent
import com.lixin.smartclassroom.api.yanxuenandu
import com.lixin.smartclassroom.app.App.wxApi
import com.lixin.smartclassroom.bean.BaseBean
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.bean.FileBean
import com.lixin.smartclassroom.bean.Small
import com.lixin.smartclassroom.bean.StudentBean
import com.lixin.smartclassroom.ext.child_id
import com.lixin.smartclassroom.ext.child_name
import com.lixin.smartclassroom.ui.MainActivity
import com.lixin.smartclassroom.ui.home.adapter.databaseDialog
import com.lixin.smartclassroom.ui.home.adapter.messageUnreadList
import com.lixin.smartclassroom.ui.home.adapter.oneText
import com.lixin.smartclassroom.ui.home.adapter.recyclerDialog
import com.lixin.smartclassroom.ui.home.adapter.selectGroupMember
import com.lixin.smartclassroom.ui.home.adapter.tab3Class
import com.lixin.smartclassroom.ui.home.tab2.activity.AddChapterAct
import com.lixin.smartclassroom.ui.home.tab2.activity.AddCourseAct
import com.lixin.smartclassroom.ui.home.tab2.activity.AddSmallChapterAct
import com.lixin.smartclassroom.ui.home.tab2.activity.CoursePermissionAct
import com.lixinkeji.base.RxManager
import com.lixinkeji.extension.addUnderLine
import com.lixinkeji.extension.applyVisible
import com.lixinkeji.extension.commonDialog
import com.lixinkeji.extension.commonLineOneButtonDialog
import com.lixinkeji.extension.dp2px
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.loadCircle
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.setRoundRectBg
import com.lixinkeji.extension.start
import com.lixinkeji.extension.text
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.visible
import com.lixinkeji.utils.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import io.reactivex.functions.Consumer
import per.goweii.anylayer.AnyLayer
import per.goweii.anylayer.Layer
import per.goweii.anylayer.ktx.doOnClickToDismiss
import per.goweii.anylayer.ktx.setContentAnimator
import per.goweii.anylayer.ktx.setSwipeDismiss
import per.goweii.anylayer.popup.PopupLayer
import per.goweii.anylayer.utils.AnimatorHelper
import per.goweii.anylayer.widget.SwipeLayout
import java.io.ByteArrayOutputStream
import java.io.File

/**
 * Description
 * Author: lwc
 * Date:2023/12/6 8:53
 */


fun Context.sourceSetDialog(
    type: String, dataListBean: DataListBean
) {
    AnyLayer.dialog(this)
        .contentView(R.layout.dialog_source_set)
        .gravity(Gravity.END)
        .setSwipeDismiss(SwipeLayout.Direction.RIGHT)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }

        }).backgroundDimAmount(0.5f).bindData {
            val tvEdit = it.getView<TextView>(R.id.tvEdit)
            val tvSend = it.getView<TextView>(R.id.tvSend)
            val tvCopy = it.getView<TextView>(R.id.tvCopy)
            val tvTop = it.getView<TextView>(R.id.tvTop)
            val tvPermission = it.getView<TextView>(R.id.tvPermission)
            val tvDelete = it.getView<TextView>(R.id.tvDelete)

            when (dataListBean.state) {
                "1" -> {
                    tvSend?.text = "发布"
                    tvSend?.isClickable = true
                }

                "2" -> {
                    when (type) {
                        "3" -> {
                            tvSend?.text = "已发布"
                            tvSend?.isClickable = false
                        }

                        else -> {
                            tvSend?.text = "下架"
                            tvSend?.isClickable = true
                        }
                    }

                }
            }


            when (dataListBean.iftop) {
                "1" -> tvTop?.text = "取消置顶"
                "2" -> tvTop?.text = "置顶"
            }

        }
        .doOnClickToDismiss(R.id.tvEdit) {
            start(AddCourseAct::class.java) {
                putExtra("type", type)
                putExtra("isEdit", "1")
                putExtra("courseid", dataListBean.id)

            }
        }.doOnClickToDismiss(R.id.tvSend) {
            when (dataListBean.state) {
                "1" -> {
                    commonDialog("发布课程",
                        content = "是否发布课程，发布后对应用户可查看",
                        cancel = "取消",
                        sure = "发布",
                        onSure = {
                            scopeNet {
                                val baseBean = fabucourse(dataListBean.id!!, "2", type)
                                if (baseBean.result == "0") {
                                    saveSuccessDialog("发布成功")
                                    sendEvent("", "refreshClassList")
                                } else
                                    toast(baseBean.resultNote.toString())

                            }
                        })
                }

                "2" -> {
                    commonDialog("下架课程",
                        content = "是否下架课程，下架后用户将不可查看",
                        cancel = "取消",
                        sure = "下架",
                        onSure = {
                            scopeNet {
                                val baseBean = fabucourse(dataListBean.id!!, "1", type)
                                if (baseBean.result == "0") {
                                    saveSuccessDialog("下架成功")
                                    sendEvent("", "refreshClassList")
                                } else
                                    toast(baseBean.resultNote.toString())

                            }
                        })

                }
            }

        }.doOnClickToDismiss(R.id.tvCopy) {
            commonDialog("复制课程",
                content = "复制成功，快去编辑信息进行发布吧",
                cancel = "取消",
                sure = "编辑",
                onSure = {
                    start(AddCourseAct::class.java) {
                        putExtra("type", type)
                        putExtra("isEdit", "1")
                        putExtra("isCopy", "1")
                        putExtra("courseid", dataListBean.id)

                    }
                })
        }.doOnClickToDismiss(R.id.tvTop) {
            when (dataListBean.iftop) {
                "1" -> {
                    scopeNet {
                        val baseBean = addtop(dataListBean.id!!, "2", type)
                        if (baseBean.result == "0") {
                            sendEvent("", "refreshClassList")
                            commonLineOneButtonDialog(
                                content = "取消置顶成功，查看课程",
                                "我知道了",
                                onSure = {

                                })
                        }
                    }
                }

                "2" -> {
                    scopeNet {
                        val baseBean = addtop(dataListBean.id!!, "1", type)
                        if (baseBean.result == "0") {
                            sendEvent("", "refreshClassList")
                            commonLineOneButtonDialog(
                                content = "置顶成功，查看课程",
                                "我知道了",
                                onSure = {

                                })
                        }
                    }
                }
            }


        }.doOnClickToDismiss(R.id.tvDelete) {
            commonDialog("删除课程",
                content = "删除后，所有数据将会清空\n且不可恢复，请谨慎操作",
                cancel = "取消",
                sure = "删除",
                onSure = {
                    scopeNet {
                        val baseBean = deletecourse(dataListBean.id!!, type)
                        if (baseBean.result == "0")
                            sendEvent("", "refreshClassList")
                        else
                            toast(baseBean.resultNote.toString())
                    }
                })
        }.doOnClickToDismiss(R.id.tvPermission) {
            start(CoursePermissionAct::class.java) {
                putExtra("courseid", dataListBean.id)
                putExtra("type", type)
                putExtra("quanxian", dataListBean.quanxian)
                putExtra("customerids", dataListBean.customerids)
            }
        }.show()
}

fun Context.addDatabaseDialog() {
    AnyLayer.dialog(this)
        .contentView(R.layout.add_database_dialog)
        .gravity(Gravity.BOTTOM)
        .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }


        }).backgroundDimAmount(0.5f).bindData {

        }.doOnClickToDismiss(com.lixinkeji.base.R.id.btnClose) { }
        .doOnClickToDismiss(R.id.tvNewFolder) {
            newFolderDialog()
        }.doOnClickToDismiss(R.id.tvUploadImg) {
            selectFolderDialog()
        }.show()
}

fun Context.newFolderDialog() {
    AnyLayer.dialog(this)
        .contentView(R.layout.new_folder)
        .gravity(Gravity.CENTER)
        .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }

        }).backgroundDimAmount(0.5f).bindData {
            val layer = it
            val tvFinish = it.getView<TextView>(R.id.tvFinish)
            val etFolderName = it.getView<EditText>(R.id.etFolderName)
            tvFinish?.onClick {
                if (etFolderName?.text()?.isEmpty() == true) {
                    toast("请输入文件夹名称")
                    return@onClick
                }
                scopeNet {
                    createfolder(etFolderName?.text()!!)
                    sendEvent("cs", "refreshFolderList")
                    layer.dismiss()
                }
            }
        }.doOnClickToDismiss(R.id.ivBack)
        .show()
}


fun Context.selectFolderDialog() {
    AnyLayer.dialog(this)
        .contentView(R.layout.select_folder)
        .gravity(Gravity.BOTTOM)
        .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }

        }).backgroundDimAmount(0.5f).bindData {
            val layer = it
            var recyclerView = it.getView<RecyclerView>(R.id.recycler)
            var btnUpload = it.getView<TextView>(R.id.btnUpload)

            scopeNet {
                val listBean = folderlist(1, 100, "1")!!
                recyclerView?.databaseDialog()?.models = listBean
            }
            btnUpload?.onClick {
                if (recyclerView?.bindingAdapter?.checkedCount == 0) {
                    toast("请选择文件夹")
                } else {
                    selectPicture(
                        (recyclerView?.bindingAdapter?.models?.get(recyclerView.bindingAdapter.checkedPosition[0]) as DataListBean).id!!,
                        it.context
                    )
                    layer.dismiss()
                }

            }


        }.doOnClickToDismiss(R.id.btnClose) { }.doOnClickToDismiss(R.id.newFolder) {
            newFolderDialog()
        }.show()
}

fun selectPicture(folderid: String, context: Context) {
    PictureSelector.create(context)
        .openGallery(SelectMimeType.ofAll())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
        .setImageEngine(GlideEngine.createGlideEngine()).setMaxSelectNum(9)
        .setMinSelectNum(0)// 最小选择数量
        .setImageSpanCount(4)// 每行显示个数
        .setSelectionMode(SelectModeConfig.SINGLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
        .isPreviewImage(true)// 是否可预览图片
        .isCameraAroundState(true)// 是否显示拍照按钮
        .isSelectZoomAnim(true)// 图片列表点击 缩放效果 默认true
        .forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                if (result != null) {
                    val files = ArrayList<File>()
                    val fileBeans = ArrayList<FileBean>()

                    for (i in 0 until result.size) {
                        val filePath: String = result[i].realPath
                        val file: File = File(filePath)
                        val fileBean = FileBean(result[i].fileName, result[i].size.toString())
                        files.add(file)
                        fileBeans.add(fileBean)
                    }

                    scopeNet {
                        val baseBean = uploadFiles(files)
                        for (i in 0 until baseBean.urls?.size!!) {
                            fileBeans[i].url = baseBean.urls!![i]
                        }
                        val bean = shangchaunfile(folderid, fileBeans)

                        if (bean.result == "0") {
                            context.saveSuccessDialog("上传成功")
                            sendEvent("", "uploadFinish")
                            val rxManager = RxManager()
                            rxManager.post("uploadFinish", "")
                        }
                    }


                }


            }

            override fun onCancel() {

            }
        })

}


fun Context.selectGroupMemberDialog(title: String, type: Int, groupid: String, courseid: String) {
    AnyLayer.dialog(this)
        .contentView(R.layout.select_group_member)
        .gravity(Gravity.BOTTOM)
        .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }

        }).backgroundDimAmount(0.5f).bindData {
            val recyclerView = it.getView<RecyclerView>(R.id.recycler)
            val tvTitle = it.getView<TextView>(R.id.tvTitle)
            val tvAddStudent = it.getView<TextView>(R.id.tvAddStudent)
            val btnSure = it.getView<TextView>(R.id.btnSure)
            val layer = it
            tvTitle?.text = title
            val listBean = ArrayList<DataListBean>()
            tvAddStudent?.applyVisible(type == 3)
            btnSure?.applyVisible(type != 3)
            recyclerView?.selectGroupMember(type, groupid)?.models = listBean
            scopeNet {
                when (type) {
                    3 -> listBean.addAll(yanxuegroupstudent(groupid, 1, 100)!!)
                    else -> listBean.addAll(canaddcustomer(courseid, type.toString())!!)
                }
                recyclerView?.bindingAdapter?.notifyDataSetChanged()
            }


            val rxManager = RxManager()
            rxManager.on("refreshDialogGroupList", Consumer<String> {
                listBean.clear()
                scopeNet {
                    when (type) {
                        3 -> listBean.addAll(yanxuegroupstudent(groupid, 1, 100)!!)
                        else -> listBean.addAll(canaddcustomer(courseid, type.toString())!!)
                    }
                    recyclerView?.bindingAdapter?.notifyDataSetChanged()
                }
            })

            btnSure!!.onClick {
                if (recyclerView?.bindingAdapter?.checkedCount == 0) {
                    toast("请选择要添加的成员")
                    return@onClick
                }
                var cid = ""
                for (i in 0 until recyclerView?.bindingAdapter?.checkedCount!!) {
                    if (cid.isEmpty()) {
                        cid =
                            (recyclerView?.bindingAdapter?.getCheckedModels<DataListBean>()
                                ?.get(i) as DataListBean).id.toString()
                    } else {
                        cid =
                            cid + "," + (recyclerView?.bindingAdapter?.getCheckedModels<DataListBean>()
                                ?.get(i) as DataListBean).id.toString()
                    }
                }
                scopeNet {
                    val baseBean = addteachers(groupid, cid, type.toString())
                    if (baseBean.result == "0") {
                        saveSuccessDialog("添加成功")
                        sendEvent("cs", "refreshGroupList")
                    } else {
                        toast(baseBean.resultNote.toString())
                    }
                }
                layer.dismiss()
            }


        }.doOnClickToDismiss(R.id.btnCancel).doOnClickToDismiss(R.id.btnClose) { }.show()
}


fun Context.messageUnreadDialog(title: String, studentBeanList: List<StudentBean>) {
    AnyLayer.dialog(this)
        .contentView(R.layout.dialog_message_unread)
        .gravity(Gravity.CENTER)
        .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }

        }).backgroundDimAmount(0.5f).bindData {
            val recyclerView = it.getView<RecyclerView>(R.id.recycler)
            val tvTitle = it.getView<TextView>(R.id.tvTitle)
            tvTitle?.text = title



            recyclerView?.messageUnreadList()?.models = studentBeanList

        }.doOnClickToDismiss(R.id.btnClose) { }.show()
}


fun Context.saveSuccessDialog(
    content: String
) {
    AnyLayer.toast().duration(1000).contentView(R.layout.save_success_dialog)
        .gravity(Gravity.CENTER)
        .bindData {
            val contentView = it.getView<TextView>(R.id.tv)
            contentView?.text = content
        }
        .show()
}


fun Context.setChapterDialog(
    view: View,
    type: Int,
    taskType: String,
    position: Int,
    dataListBean: DataListBean? = null,
    small: Small? = null
) {
    AnyLayer.popup(view)
        .direction(PopupLayer.Align.Direction.VERTICAL)
        .horizontal(PopupLayer.Align.Horizontal.CENTER)
        .vertical(PopupLayer.Align.Vertical.BELOW)
        .inside(true)
        .outsideTouchedToDismiss(true)
        .contentView(R.layout.dialog_set_chapter)
        .bindData {
            val btnEdit = it.getView<TextView>(R.id.btnEdit)
            val btnAddChapter = it.getView<TextView>(R.id.btnAddChapter)
            val btnDelete = it.getView<TextView>(R.id.btnDelete)
            val btnStart = it.getView<TextView>(R.id.btnStart)
            btnEdit?.addUnderLine()
            btnAddChapter?.addUnderLine()
            btnDelete?.addUnderLine()
            btnStart?.addUnderLine()
            when(taskType){
                "3"->btnStart?.gone()
                else->btnStart?.visible()
            }
            if (type == 2) {
                btnAddChapter?.gone()
                when (small?.state) {
                    "1" -> btnStart?.text = "关闭"
                    else -> btnStart?.text = "开启"
                }
            } else {
                when (dataListBean?.state) {
                    "1" -> btnStart?.text = "关闭"
                    else -> btnStart?.text = "开启"
                }
            }
        }.doOnClickToDismiss(R.id.btnEdit) {
            if (type == 1) {
                start(AddChapterAct::class.java) {
                    putExtra("dataListBean", dataListBean)
                    putExtra("isEdit", true)
                    putExtra("type", taskType)
                }
            } else if (type == 2) {
                start(AddSmallChapterAct::class.java) {
                    putExtra("small", small)
                    putExtra("dataListBean", dataListBean)
                    putExtra("isEdit", true)
                    putExtra("type", taskType)
                }
            }


        }.doOnClickToDismiss(R.id.btnAddChapter) {
            if (type == 1) {
                start(AddSmallChapterAct::class.java) {
                    putExtra("dataListBean", dataListBean)
                    putExtra("isEdit", false)
                    putExtra("type", taskType)
                }
            }

        }.doOnClickToDismiss(R.id.btnDelete) {
            commonDialog("删除章节",
                content = "删除后，所有数据将会清空\n且不可恢复，请谨慎操作",
                cancel = "取消",
                sure = "删除",
                onSure = {
                    scopeNet {
                        if (type == 1) {
                            deletebigzhangjie(dataListBean?.id.toString())
                            sendEvent(position, "deleteBigChapter")
                            sendEvent("", "refreshDaGang")
                        } else {
                            deletesmallzhangjie(small?.id.toString())
                            small?.parentPosition = position
                            sendEvent(small!!, "deleteSmallChapter")
                            sendEvent("", "refreshDaGang")

                        }
                    }
                })
        }.doOnClickToDismiss(R.id.btnStart) {
            scopeNet {
                if (type == 1) {
                    when (dataListBean?.state) {
                        "1" -> {
                            openorclosezhangjie(dataListBean?.id.toString(), "2")
                        }

                        "2" -> {
                            openorclosezhangjie(dataListBean?.id.toString(), "1")
                        }
                    }
                    sendEvent(position, "openOrCloseBigChapter")

                } else {
                    when (small?.state) {
                        "1" -> {
                            openorclosesmallzhangjie(small.id.toString(), "2")

                        }

                        "2" -> {
                            openorclosesmallzhangjie(small.id.toString(), "1")

                        }
                    }
                    small?.parentPosition = position
                    sendEvent(small!!, "openOrCloseSmallChapter")
                }
            }
        }
        .show()
}


fun Context.setPermissionDialog(view: View) {
    AnyLayer.popup(view)
        .direction(PopupLayer.Align.Direction.VERTICAL)
        .horizontal(PopupLayer.Align.Horizontal.ALIGN_RIGHT)
        .vertical(PopupLayer.Align.Vertical.BELOW)
        .inside(true)
        .backgroundColorInt(Color.parseColor("#80000000"))
        .outsideTouchedToDismiss(true)
        .contentView(R.layout.dialog_set_permission)
        .bindData {

        }.doOnClickToDismiss(R.id.btnAll) {

        }.doOnClickToDismiss(R.id.btnStudent) {

        }.doOnClickToDismiss(R.id.btnSomePerson) {

        }.doOnClickToDismiss(R.id.btnOnlySelf) {

        }.doOnClickToDismiss(R.id.btnParent) {

        }
        .show()
}


fun Context.questionAnalysisDialog(type: String, dataListBean: DataListBean) {
    AnyLayer.dialog(this)
        .contentView(R.layout.dialog_question_analysis)
        .gravity(Gravity.BOTTOM)
        .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }

        }).backgroundDimAmount(0.5f).bindData {
            val imgAd = it.getView<ImageView>(R.id.imgAd)
            val llAnswer = it.getView<LinearLayout>(R.id.llAnswer)
            val tvRightAnswer = it.getView<TextView>(R.id.tvRightAnswer)
            val tvAnalysis = it.getView<TextView>(R.id.tvAnalysis)
            tvRightAnswer?.text = dataListBean.right
            tvAnalysis?.text = dataListBean.jiexi

            when (type) {
                "1" -> {
                    llAnswer?.visible()
                    imgAd?.gone()
                }

                "2" -> {
                    llAnswer?.gone()
                    imgAd?.visible()
                }
            }

        }.doOnClickToDismiss(R.id.btnClose) { }.show()
}


fun Context.eventRegistration() {
    AnyLayer.dialog(this)
        .contentView(R.layout.dialog_event_registration)
        .gravity(Gravity.CENTER)
        .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }

        }).backgroundDimAmount(0.5f).bindData {

        }.doOnClickToDismiss(R.id.sure) {
            sendEvent("cs", "finishAct")
        }.show()
}


fun Context.bindStudentDialog(
    title: String,
    type: Int,
    sureText: String? = null,
    baseBean: BaseBean? = null
) {
    AnyLayer.dialog(this).contentView(R.layout.dialog_bind_student)
        .outsideTouchedToDismiss(false)
        .cancelableOnClickKeyBack(false).backgroundDimAmount(0.5f).bindData {

            val headImg = it.getView<ImageView>(R.id.headImg)
            val tvName = it.getView<TextView>(R.id.tvName)
            val tvTitle = it.getView<TextView>(R.id.title)
            val sure = it.getView<TextView>(R.id.sure)
            val tvStudentNo = it.getView<TextView>(R.id.tvStudentNo)
            val tvRole = it.getView<TextView>(R.id.tvRole)
            val tvInteractionCode = it.getView<TextView>(R.id.tvInteractionCode)
            tvTitle?.text = title
            if (sureText != null) {
                if (sureText.isNotEmpty())
                    sure?.text = sureText
            }
            if (baseBean != null) {
                headImg?.loadCircle(baseBean.image!!)
                tvName?.text = baseBean.name
                tvStudentNo?.text = "学号：" + baseBean.xuehao
                tvInteractionCode?.text = "互动码：" + baseBean.hudong
            }
            when (baseBean?.leixing) {
                "1" -> tvRole?.text = "学生"
                "2" -> tvRole?.text = "老师"
                "3" -> tvRole?.text = "家长"
            }


        }.doOnClickToDismiss(R.id.cancel) {

        }
        .doOnClickToDismiss(R.id.sure) {
            scopeNet {
                if (baseBean != null) {
                    when (type) {
                        1 -> {
                            val resultBean = bindcustomer(baseBean.id!!)
                            if (resultBean.result == "0") {
                                start(MainActivity::class.java)
                                child_id = baseBean.id
                                child_name = baseBean.name!!

                            } else {
                                toast(resultBean.resultNote.toString())
                            }
                        }

                        2 -> {
                            sendEvent(baseBean, "addStudent")
                        }
                    }


                }
            }


        }.show()
}

fun Context.recyclerDialog(
    type: Int,
    title: String,
    cancel: String = "",
    sure: String = "",
    textView: TextView? = null,
    currentPosition: Int? = null,
    recyclerView: RecyclerView? = null,
    onCancel: (() -> Unit)? = null,
    onSure: (() -> Unit)? = null,
) {
    AnyLayer.dialog(this).contentView(R.layout.dialog_recycler).outsideTouchedToDismiss(true)
        .cancelableOnClickKeyBack(true).backgroundDimAmount(0.5f).bindData {
            val layer = it
            val titleView = it.getView<TextView>(R.id.title)
            val recycler = it.getView<RecyclerView>(R.id.recycler)
            val sureView = it.getView<TextView>(R.id.sure)
            val cancelView = it.getView<TextView>(R.id.cancel)
            val llButton = it.getView<LinearLayout>(R.id.llButton)

            sureView.applyVisible(sure.isNotEmpty())
            cancelView.applyVisible(cancel.isNotEmpty())
            titleView?.text = title
            sureView?.text = sure
            cancelView?.text = cancel

            val listBean = ArrayList<DataListBean>()
            when (type) {
                1 -> {
                    scopeNet {
                        listBean.addAll(classlist(1, 1000)!!)
                        recycler?.bindingAdapter?.notifyDataSetChanged()
                    }
                }

                2 -> {
                    scopeNet {
                        listBean.addAll(lablelist()!!)
                        recycler?.bindingAdapter?.notifyDataSetChanged()
                    }
                }

                3 -> {
                    scopeNet {
                        listBean.addAll(getzhutitype()!!)
                        recycler?.bindingAdapter?.notifyDataSetChanged()
                    }
                }

                4 -> {
                    scopeNet {
                        listBean.addAll(yanxuenandu()!!)
                        recycler?.bindingAdapter?.notifyDataSetChanged()
                    }
                }

                5 -> {
                    scopeNet {
                        listBean.addAll(yanxuebiaoqian()!!)
                        recycler?.bindingAdapter?.notifyDataSetChanged()
                    }
                }

                6, 9 -> {
                    scopeNet {
                        listBean.addAll(weidulist()!!)
                        recycler?.bindingAdapter?.notifyDataSetChanged()
                    }
                }

                7 -> {
                    scopeNet {
                        listBean.addAll(huizhanglist()!!)
                        recycler?.bindingAdapter?.notifyDataSetChanged()
                    }
                }

                8 -> {
                    scopeNet {
                        listBean.addAll(yanxuebaominglist()!!)
                        recycler?.bindingAdapter?.notifyDataSetChanged()
                    }
                }

            }


            when (type) {
                5 -> {
                    llButton?.visible()
                    recycler?.recyclerDialog(5)?.apply {
                        R.id.tv?.onClick {
                            setChecked(modelPosition, !checkedPosition.contains(modelPosition))
                        }
                    }?.models = listBean

                    sureView?.onClick {
                        val listBean = recycler?.bindingAdapter?.getCheckedModels<DataListBean>()
                        recyclerView?.oneText(3)?.models = listBean
                        sendEvent("", "updateBiaoqianType")
                        layer.dismiss()
                    }

                }

                8 -> {
                    llButton?.visible()
                    recycler?.recyclerDialog(8)?.apply {
                        R.id.tv?.onClick {
                            setChecked(modelPosition, !checkedPosition.contains(modelPosition))
                        }
                    }?.models = listBean

                    sureView?.onClick {
                        val listBean = recycler?.bindingAdapter?.getCheckedModels<DataListBean>()
                        var baominginfo = ""
                        var baominginfoId = ""
                        for (i in 0 until listBean?.size!!) {
                            if (baominginfo.isEmpty()) {
                                baominginfo = listBean[i].name!!
                            } else {
                                baominginfo += "," + listBean[i].name!!
                            }
                            if (baominginfoId.isEmpty()) {
                                baominginfoId = listBean[i].id!!
                            } else {
                                baominginfoId += "," + listBean[i].id!!
                            }
                        }

                        textView?.text = baominginfo
                        sendEvent(baominginfoId, "baominginfoId")
                        layer.dismiss()
                    }
                }

                7 -> {
                    recycler?.tab3Class()?.apply {
                        R.id.ll.onClick {
                            sendEvent(
                                (models?.get(modelPosition) as DataListBean),
                                "yinzhangUrl"
                            )
                            layer.dismiss()
                        }
                    }?.models = listBean
                }

                else -> {
                    recycler?.recyclerDialog(type)?.apply {
                        R.id.tv?.onClick {
                            textView?.text = this.findView<TextView>(R.id.tv).text
                            this.findView<TextView>(R.id.tv)
                                .setRoundRectBg(Color.parseColor("#4B6AEF"), dp2px(10f).toInt())
                            when (type) {
                                1 -> sendEvent(
                                    (models?.get(modelPosition) as DataListBean),
                                    "suoshuclass"
                                )

                                2 -> sendEvent(
                                    (models?.get(modelPosition) as DataListBean),
                                    "courselable"
                                )

                                3 -> sendEvent(
                                    (models?.get(modelPosition) as DataListBean),
                                    "suoshufenlei"
                                )

                                4 -> sendEvent(
                                    (models?.get(modelPosition) as DataListBean),
                                    "yanxuenandu"
                                )

                                6 -> sendEvent(
                                    (models?.get(modelPosition) as DataListBean),
                                    "weidu"
                                )

                                9 -> {
                                    val dataListBean = models?.get(modelPosition) as DataListBean
                                    dataListBean.selectPosition = currentPosition.toString()
                                    sendEvent(
                                        dataListBean,
                                        "weiduEvaluate"
                                    )
                                }

                            }

                            layer.dismiss()
                        }
                    }?.models = listBean
                }

            }


        }.doOnClickToDismiss(R.id.cancel) { if (onCancel != null) onCancel() }.show()
}


fun Context.commonEditTextDialog(
    type: Int,
    fildid: String,
    title: String,
    hint: String = "",
    cancel: String = "",
    sure: String = "",
    onCancel: (() -> Unit)? = null,
    onSure: (() -> Unit)? = null,
    textview: TextView? = null
) {
    AnyLayer.dialog(this).contentView(com.lixinkeji.base.R.layout.common_dialog)
        .outsideTouchedToDismiss(false)
        .cancelableOnClickKeyBack(false).backgroundDimAmount(0.5f).bindData {
            val layer = it
            val contentView = it.getView<TextView>(com.lixinkeji.base.R.id.content)
            val etContent = it.getView<EditText>(com.lixinkeji.base.R.id.etContent)
            val titleView = it.getView<TextView>(com.lixinkeji.base.R.id.title)
            val sureView = it.getView<TextView>(com.lixinkeji.base.R.id.sure)
            val cancelView = it.getView<TextView>(com.lixinkeji.base.R.id.cancel)

            sureView.applyVisible(sure.isNotEmpty())
            cancelView.applyVisible(cancel.isNotEmpty())
            contentView?.gone()
            etContent?.visible()
            etContent?.hint = hint
            titleView?.text = title
            sureView?.text = sure
            cancelView?.text = cancel
            sureView?.onClick {
                when (type) {
                    1 -> {
                        if (etContent.text().isEmpty()) {
                            toast("请输入名称")
                            return@onClick
                        }
                        scopeNet {
                            val baseBean = updatejingcaifile(etContent.text(), fildid)
                            if (baseBean.result == "0") {
                                saveSuccessDialog("修改成功")
                                sendEvent("cs", "refreshList")
                                layer.dismiss()
                            }
                        }
                    }

                    2 -> {
                        if (etContent.text().isEmpty()) {
                            toast("请输入评语")
                            return@onClick
                        }
                        textview?.text = etContent.text()
                        sendEvent("cs","refreshButtonUI")
                        layer.dismiss()

                    }

                    3 -> {
                        if (etContent.text().isEmpty()) {
                            toast("请输入小组名称")
                            return@onClick
                        }
                        scopeNet {
                            val baseBean = createyanxuegroup(etContent.text(), fildid)
                            if (baseBean.result == "0") {
                                saveSuccessDialog("小组创建成功")
                                sendEvent("cs", "refreshGroupList")
                                layer.dismiss()
                            }
                        }
                    }

                    4 -> {
                        if (etContent.text().isEmpty()) {
                            toast("请输入文件夹名称")
                            return@onClick
                        }
                        scopeNet {
                            val baseBean = updatefolder(fildid, etContent.text())
                            if (baseBean.result == "0") {
                                saveSuccessDialog("重命名成功")
                                sendEvent("cs", "refreshFolderList")
                                layer.dismiss()
                            }
                        }
                    }
                }

            }

        }.doOnClickToDismiss(com.lixinkeji.base.R.id.cancel) { if (onCancel != null) onCancel() }
        .show()
}


fun Context.shareDialog(courseId: String, coursetitle: String) {
    AnyLayer.dialog(this)
        .contentView(com.lixinkeji.base.R.layout.share_dialog)
        .gravity(Gravity.BOTTOM)
        .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }

        }).backgroundDimAmount(0.5f).bindData {

        }.doOnClickToDismiss(com.lixinkeji.base.R.id.tvFriend) {
            //初始化一个WXWebpageObject，填写url
            val webpage = WXWebpageObject()
            webpage.webpageUrl = "http://121.41.179.145/h5/index.html#/?id=$courseId"

//用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
            val msg = WXMediaMessage(webpage)
            msg.title = "智慧课堂"
            msg.description = coursetitle
            val thumbBmp = BitmapFactory.decodeResource(resources, R.drawable.logo_smartcourse)
            val stream = ByteArrayOutputStream()
            thumbBmp.compress(Bitmap.CompressFormat.JPEG, 100, stream)
            val imageInByte = stream.toByteArray()
            msg.thumbData = imageInByte

//构造一个Req
            val req = SendMessageToWX.Req()
            req.transaction = "webpage"
            req.message = msg
            req.scene = SendMessageToWX.Req.WXSceneSession

//调用api接口，发送数据到微信
            wxApi.sendReq(req)
        }.doOnClickToDismiss(com.lixinkeji.base.R.id.tvPyq) {
//初始化一个WXWebpageObject，填写url
            val webpage = WXWebpageObject()
            webpage.webpageUrl = "http://121.41.179.145/h5/index.html#/?id=$courseId"


//用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
            val msg = WXMediaMessage(webpage)
            msg.title = "智慧课堂"
            msg.description = coursetitle
            val thumbBmp = BitmapFactory.decodeResource(resources, R.drawable.logo_smartcourse)
            val stream = ByteArrayOutputStream()
            thumbBmp.compress(Bitmap.CompressFormat.JPEG, 100, stream)
            val imageInByte = stream.toByteArray()
            msg.thumbData = imageInByte

//构造一个Req
            val req = SendMessageToWX.Req()
            req.transaction = "webpage"
            req.message = msg
            req.scene = SendMessageToWX.Req.WXSceneTimeline

//调用api接口，发送数据到微信
            wxApi.sendReq(req)
        }.doOnClickToDismiss(com.lixinkeji.base.R.id.btnClose) { }.show()
}

fun Context.longClickDialog(folderid: String) {
    AnyLayer.dialog(this)
        .contentView(R.layout.long_click_dialog)
        .gravity(Gravity.BOTTOM)
        .setSwipeDismiss(SwipeLayout.Direction.BOTTOM)
        .setContentAnimator(object :
            Layer.AnimatorCreator {
            override fun createInAnimator(target: View): Animator {
                return AnimatorHelper.createBottomInAnim(target)
            }

            override fun createOutAnimator(target: View): Animator {
                return AnimatorHelper.createBottomOutAnim(target)
            }

        }).backgroundDimAmount(0.5f).bindData {

        }.doOnClickToDismiss(R.id.tvDelete) {
            commonDialog("删除文件夹", "是否删除，删除后数据不可以恢复", "返回", "删除", onSure = {
                scopeNet {
                    deletefolder(folderid)
                    saveSuccessDialog("删除成功")
                    sendEvent("", "refreshFolderList")
                }
            })

        }.doOnClickToDismiss(R.id.tvRename) {
            commonEditTextDialog(
                4,
                folderid,
                "重命名",
                "请输入文件夹名称",
                "返回",
                "确定"
            )
        }.doOnClickToDismiss(R.id.btnClose) { }.show()
}




